using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Threading;
using ALC.Core.ViewModels.Workpiece;
using WPFCommon.ViewModels.Base;

namespace ALC.Core.ViewModels.Table
{
    /// <summary>
    /// Log items to Ui without queuing
    /// </summary>
    public class WorkpieceTableListViewModel : ViewModelBase
    {
        #region private field
        
        private readonly int _maxSize;
        private readonly double _preservePercent;

        #endregion

        #region prop

        public ObservableCollection<WorkpieceViewModel> WorkpieceViewModels { get; set; } =
            new ObservableCollection<WorkpieceViewModel>();

        #endregion

        #region api

        public void Add(WorkpieceViewModel workpieceViewModel)
        {
            System.Windows.Application.Current.Dispatcher?.BeginInvoke(DispatcherPriority.Background, new Action(() =>
            {
                WorkpieceViewModels.Insert(0, workpieceViewModel);
                if (WorkpieceViewModels.Count > _maxSize)
                {
                    WorkpieceViewModels =
                        new ObservableCollection<WorkpieceViewModel>(
                            WorkpieceViewModels.Take((int) (_maxSize * _preservePercent)));
                }
            }));
        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="maxSize">Max size of the ObservableCollection</param>
        /// <param name="preservePercent">Percent of items in ObservableCollection to preserve if  </param>
        public WorkpieceTableListViewModel(int maxSize, double preservePercent = 0.7)
        {
            _maxSize = maxSize;
            _preservePercent = preservePercent;
        }

    }
}